package org.dizem.intellipainter.component.media;

import org.dizem.intellipainter.util.AppletUtil;

import javax.swing.*;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * User: dizem@126.com
 * Time: 12-2-18 下午11:15
 */
public class MusicButton extends JToggleButton {
	private static final Font FONT = new Font("微软雅黑", Font.PLAIN, 12);
	private static final Dimension SIZE = new Dimension(60, 33);
	private AudioClip sound;

	public void init(Applet applet) {
		sound = AppletUtil.getMusic(applet, "music.mid");
	}

	@Override
	public void paint(Graphics g) {
		super.paint(g);
		Graphics2D g2d = (Graphics2D) g;
		RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
		g2d.setRenderingHints(qualityHints);
		if (isSelected()) {
			g.drawString("停止播放", 5, 22);
		} else {
			g.drawString("播放音乐", 5, 22);
		}
	}

	public MusicButton() {
		setFont(FONT);
		setDoubleBuffered(true);
		setMaximumSize(SIZE);
		setMinimumSize(SIZE);
		setPreferredSize(SIZE);
		addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println(sound != null);
				if (isSelected()) {
					if (sound != null) {
						sound.loop();
					}
				} else {
					if (sound != null) {
						sound.stop();
					}
				}
				repaint();
			}
		});
	}
}
